package com.example.nio.netty.server;

import com.example.nio.netty.protoco.request.MessageRequest;
import com.example.nio.netty.protoco.response.MessageResponse;
import com.example.nio.netty.session.Session;
import com.example.nio.netty.session.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequest msg) throws Exception {
        Channel channel = SessionUtil.getChannel(msg.getToUserId());
        Session session = SessionUtil.getSession(ctx.channel());
        System.out.println(msg.toString());
        if (channel != null){
            channel.writeAndFlush(new MessageResponse(session.getUserName(), msg.getToUserId() ,msg.getMessage()));
        }
    }

}
